﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Threading;
using System.Web.Security;
using System.Web;
using KL.Store.Core.Domain;
using KL.Store.Core;
using System.Globalization;
using System.IO;

namespace KL.Store.Core.Web
{
    public abstract partial class BaseController : Controller
    {
        #region ChildAction HttpPost Ajax control Deny for GET

        public class ChildAttribute : ActionMethodSelectorAttribute
        {
            private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Post);
            public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
            {
                var isPost = _innerAttribute.IsValidForRequest(controllerContext, methodInfo);
                var isChildAction = controllerContext.IsChildAction;
                var isAjax = controllerContext.RequestContext.HttpContext.Request.IsAjaxRequest();

                return isChildAction || (isAjax && isPost);
            }
        }

        #endregion

        #region ExitHttpsIfNotRequiredAttribute

        //[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
        //public class RetainHttpsAttribute : Attribute
        //{
        //}

        //public class ExitHttpsIfNotRequiredAttribute : FilterAttribute, IAuthorizationFilter
        //{
        //    public void OnAuthorization(AuthorizationContext filterContext)
        //    {
        //        // abort if it's not a secure connection  
        //        if (!filterContext.HttpContext.Request.IsSecureConnection) return;

        //        // abort if a [RequireHttps] attribute is applied to controller or action  
        //        if (filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return;
        //        if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return;

        //        // abort if a [RetainHttps] attribute is applied to controller or action  
        //        if (filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(RetainHttpsAttribute), true).Length > 0) return;
        //        if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(RetainHttpsAttribute), true).Length > 0) return;

        //        // abort if it's not a GET request - we don't want to be redirecting on a form post  
        //        if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) return;

        //        // redirect to HTTP  
        //        string url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
        //        filterContext.Result = new RedirectResult(url);
        //    }
        //}

        #endregion

        #region eStoreUser

        public ActiveAccount eStoreUser
        {
            get
            {
                if (Session["eStoreUser"] == null)
                {
                    //Logger.Write("BaseController - Session Null, Creating One");
                    FormsAuthentication.SignOut();
                    ActiveAccount _eStoreUser = new ActiveAccount();
                    Session["eStoreUser"] = _eStoreUser;
                }
                return (ActiveAccount)Session["eStoreUser"];
            }
        }

        #endregion

        #region InfoMessage , ErrorMessage

        public ActionResult InfoMessage(string msg)
        {
            return JavaScript("InfoMessage('" + msg + "', false)");
        }

        public ActionResult ErrorMessage(string msg)
        {
            return JavaScript("InfoMessage('" + msg + "', true)");
        }

        #endregion

        #region Execute

        protected override void Execute(System.Web.Routing.RequestContext requestContext)
        {
            if (requestContext.HttpContext != null)
            {
                //eStoreUser = (ActiveAccount)Session["eStoreUser"];

                //if (eStoreUser == null)
                //{
                //    eStoreUser.AccountId = -1;
                //    eStoreUser.CultureInfo = "tr-TR";
                //    eStoreUser.Theme = "Default";
                //    eStoreUser.ListType = "Grid";
                //    eStoreUser.PageItemCount = 6;
                //    eStoreUser.FirstName = "";
                //    eStoreUser.LastName = "";

                //    Session["eStoreUser"] = eStoreUser;
                //}

                //System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(eStoreUser.CultureInfo);
                //Thread thread = Thread.CurrentThread;

                //thread.CurrentCulture = ci;
                //thread.CurrentUICulture = ci;

                //Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR");
                //Thread.CurrentThread.CurrentUICulture = new CultureInfo("tr-TR");

                if (!User.Identity.IsAuthenticated)
                {
                    FormsAuthentication.SignOut();
                }
            }

            try
            {
                ViewData["StoreUserName"] = (eStoreUser.FirstName + ' ' + eStoreUser.LastName).TrimEnd();
                ViewData["Controller"] = requestContext.RouteData.Values["controller"];
                ViewData["Action"] = requestContext.RouteData.Values["action"];
                ViewData["PageCode"] = requestContext.RouteData.Values["controller"] + "/" + requestContext.RouteData.Values["action"];
            }
            catch
            {
                ViewData["PageCode"] = null;
            }
            base.Execute(requestContext);
        }

        #endregion

        #region OnException

        protected override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled)
            {
                return;
            }
            Session["###eStoreError"] = filterContext.Exception;

            filterContext.Result = new ContentResult
            {
                Content = "<script>window.location='/Error'</script>"
            };

            filterContext.ExceptionHandled = true;
        }

        #endregion

        #region TCKimlikMod

        public static bool TCKimlikMod(string tcKimlikNo)
        {
            bool returnvalue = false;
            if (!string.IsNullOrEmpty(tcKimlikNo) && tcKimlikNo.Length == 11)
            {
                Int64 ATCNO, BTCNO, TcNo;
                long C1, C2, C3, C4, C5, C6, C7, C8, C9, Q1, Q2;

                TcNo = Int64.Parse(tcKimlikNo);

                ATCNO = TcNo / 100;
                BTCNO = TcNo / 100;

                C1 = ATCNO % 10; ATCNO = ATCNO / 10;
                C2 = ATCNO % 10; ATCNO = ATCNO / 10;
                C3 = ATCNO % 10; ATCNO = ATCNO / 10;
                C4 = ATCNO % 10; ATCNO = ATCNO / 10;
                C5 = ATCNO % 10; ATCNO = ATCNO / 10;
                C6 = ATCNO % 10; ATCNO = ATCNO / 10;
                C7 = ATCNO % 10; ATCNO = ATCNO / 10;
                C8 = ATCNO % 10; ATCNO = ATCNO / 10;
                C9 = ATCNO % 10; ATCNO = ATCNO / 10;
                Q1 = ((10 - ((((C1 + C3 + C5 + C7 + C9) * 3) + (C2 + C4 + C6 + C8)) % 10)) % 10);
                Q2 = ((10 - (((((C2 + C4 + C6 + C8) + Q1) * 3) + (C1 + C3 + C5 + C7 + C9)) % 10)) % 10);

                returnvalue = ((BTCNO * 100) + (Q1 * 10) + Q2 == TcNo);
            }
            return returnvalue;
        }
        #endregion
    }
}
